package com.ruoyi.transaction.service.impl;

import com.google.common.collect.Lists;
import com.ruoyi.common.constant.OrderStatusConstants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.transaction.domain.Order;
import com.ruoyi.transaction.domain.OrderItem;
import com.ruoyi.transaction.domain.OrderItemTmp;
import com.ruoyi.transaction.mapper.OrderMapper;
import com.ruoyi.transaction.service.IOrderItemService;
import com.ruoyi.transaction.service.IOrderItemTmpService;
import com.ruoyi.transaction.service.IOrderService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by gzdmt01 on 2019/4/18.
 */
@Service
public class OrderService implements IOrderService {

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private IOrderItemService orderItemService;
    @Autowired
    private IOrderItemTmpService iOrderItemTmpService;

    @Override
    @Transactional
    public AjaxResult add(Order order, String orderItemTmpIds, Long userId) {
        if(StringUtils.isBlank(orderItemTmpIds)){
            return  AjaxResult.error("未勾选Item");
        }
        orderMapper.insert(order);
        Integer orderId = order.getOrderId();
        Integer[] ids= com.ruoyi.common.utils.StringUtils.StringToInt(orderItemTmpIds.split(","));
        List<OrderItemTmp> orderItemTmpList = iOrderItemTmpService.listOrederItemTmpByIds(userId,ids);
        List<OrderItem> oderItemList = tranToOrderItemList(orderItemTmpList, orderId);
        orderItemService.batchInsert(oderItemList);
        return AjaxResult.success();
    }

    private List<OrderItem> tranToOrderItemList(List<OrderItemTmp> orderItemTmpList, Integer orderId) {
        ArrayList<OrderItem> oderItemList = Lists.newArrayList();
        OrderItem orderItem = null;
        for (int i = 0; i < orderItemTmpList.size(); i++) {
            OrderItemTmp orderItemTmp =  orderItemTmpList.get(i);
            orderItem=tranToOrderItem(orderItemTmp, orderId);
            oderItemList.add(orderItem);
        }
        return oderItemList;
    }

    private OrderItem tranToOrderItem(OrderItemTmp orderItemTmp, Integer orderId) {
        OrderItem orderItem = OrderItem.builder().orderId(orderId)
                .declaredValue(orderItemTmp.getDeclaredValue())
                .expressCompanyId(orderItemTmp.getExpressCompanyId())
                .expressNo(orderItemTmp.getExpressNo())
                .goodsName(orderItemTmp.getGoodsName()).qty(orderItemTmp.getQty())
                .remark(orderItemTmp.getRemark())
                .weight(BigDecimal.ZERO)
                .status(OrderStatusConstants.DRAFTED)
                .build();
        return  orderItem;
    }
}
